package com.sdry.web.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Controller;

import com.sdry.model.jyy.Receive;
import com.sdry.model.lz.CodeMark;
import com.sdry.model.lz.Materiel;
import com.sdry.model.tdd.receiveTips.ReceiveTips;
import com.sdry.model.tdd.receiveTips.ReceiveTipsDetails;
import com.sdry.service.inventoryInfoOnlyCountRejects.InventoryInfoOnlyCountRejectsService;
import com.sdry.service.tdd.receiveTips.ReceiveTipsDetailsService;
import com.sdry.service.tdd.receiveTips.ReceiveTipsService;
import com.sdry.utils.DateUtil;
import com.sdry.utils.PushExample;

@Controller
public class DataSourceInitListener implements ApplicationListener<ContextRefreshedEvent> {

	@Resource InventoryInfoOnlyCountRejectsService infoOnlyCountRejectsService;
	@Resource ReceiveTipsService receiveTipsService;
	@Resource ReceiveTipsDetailsService receiveTipsDetailsService;
	
	private static final Log LOGGER = LogFactory.getLog(DataSourceInitListener.class);

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		try {
			// 在web项目中（spring mvc），系统会存在两个容器，一个是root application context
			// ,另一个就是我们自己的 projectName-servlet context（作为root application
			// context的子容器）。
			// 这种情况下，就会造成onApplicationEvent方法被执行两次。为了避免这个问题，我们可以只在root
			// application context初始化完成后调用逻辑代码，其他的容器的初始化完成，则不做任何处理。
			if (event.getApplicationContext().getParent() == null) {
				// 需要实现的功能
//				System.out.println("随项目启动方式二----------------》");
				try {
					int ihour = 2;
					Integer cacheTime = 1000 * 60 * 60 * 2;  
			        Timer timer = new Timer();  
			        // (TimerTask task, long delay, long period)任务，延迟时间，多久执行  
			        timer.schedule(new TimerTask() {  
			            @Override  
			            public void run() {  
			                //System.out.println(new Date());  
			                String send_date = getBeforeByHourTime(ihour);
			                String location_code = "DJ";
			                String people = "";
			                String date = DateUtil.dateFormat3();
							List<Receive> receiveList = infoOnlyCountRejectsService.selectReceiveByLocation_codeAndSend_date(location_code, send_date);
							for (int i = 0; i < receiveList.size(); i++) {
								List<String> codeList = new ArrayList<>();
								List<Materiel> materielList = infoOnlyCountRejectsService.select_materielByLocation_codeAndSend_date(location_code, send_date, receiveList.get(i).getReceiveNumber());
								for (Materiel materiel : materielList) {
									List<CodeMark> codeMarkList = infoOnlyCountRejectsService.selectCodeByLocation_codeAndSend_dateAndReceive_number(location_code, send_date, receiveList.get(i).getReceiveNumber(),materiel.getId());
									int codeNum = 0;
									for (CodeMark codeMark : codeMarkList) {
										codeNum = codeNum + codeMark.getNum();
										codeList.add(codeMark.getCode());
									}
									ReceiveTips receiveTips = new ReceiveTips();
									receiveTips.setSendNumber(receiveList.get(i).getReceiveNumber());
									receiveTips.setSap(materiel.getMateriel_num());
									receiveTips.setSendDate(receiveList.get(i).getSendDate());
									receiveTips.setTuisongtime(date);
									receiveTips.setCodenum(codeNum);
									Long id = receiveTipsService.insert(receiveTips);
									if(null != id && id > 0){
										for (CodeMark codeMark : codeMarkList) {
											ReceiveTipsDetails receiveTipsDetails = new ReceiveTipsDetails();
											receiveTipsDetails.setCode(codeMark.getCode());
											receiveTipsDetails.setRtid(id);
											receiveTipsDetailsService.insert(receiveTipsDetails);
										}
									}
								}
								String codes = String.join(",", codeList);
								String content = "收货单"+receiveList.get(i).getReceiveNumber() + "：" + codes + "-" + "已收货超过两小时未上架";
								System.out.println(content);
								PushExample.testSendPush(content , "收货报警", people, "0");
							}
			            }  
			        }, 1000, cacheTime); 
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			LOGGER.error("StartGateServiceData", e);
		}
	}
	
	/**
	 * 得到当前时间的前N小时
	 * 
	 * @param d
	 * @param day
	 * @return
	 */
	public String getBeforeByHourTime(int ihour){
		String returnstr = ""; 
		Calendar calendar = Calendar.getInstance(); 
		calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - ihour); 
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		returnstr = df.format(calendar.getTime()); 
		return returnstr;
		}
}